<script setup lang='ts'>
import {ref,onMounted,watch,nextTick,onBeforeUnmount} from 'vue'
import {primaryColor_hex} from "@/theme/config"
import {deepClone} from "@/common/utils"
import sortable from 'sortablejs'

const props=withDefaults(
  defineProps<{
    list:{[key:string]:any}
    idKeyName?:string
  }>(),
  {
    idKeyName:'prop',
  }
)

const emits=defineEmits(['confirm'])

const visible=ref(false)
const preCheckedList=ref<string[]>([])
const checkedList=ref<string[]>([])
const checkedAll=ref(false)
const halfchecked=ref(false)
const initList=ref<TableColConfig[]>([])
const list=ref<TableColConfig[]>([])
const idKey=props.idKeyName
const listElRef = ref()
const sortKeys=ref<string[]>([])
const initCheckedList=ref<string[]>([])
let sortableInstance:any

onBeforeUnmount(()=>{
   removeSortable()
})

onMounted(()=>{
  initList.value=deepClone(props.list)
  list.value=deepClone(props.list,false)
  list.value.forEach(v=>{
    if(!(Object.keys(v).includes('checked') && !v.checked))  
    checkedList.value.push(v[idKey])     
  })
  initCheckedList.value=deepClone(checkedList.value,false)
  if(checkedList.value.length==initList.value.length) {
      halfchecked.value=false
      checkedAll.value=true
  }
  preCheckedList.value=[...checkedList.value]
  initSortable()
})

watch(()=>props.list,
(v)=>{
  //list.value=v as tableColConfig[]
},{immediate:false})

watch(checkedList,(list)=>{
  //console.log(list,list.length)
  if(!list.length) {
    checkedAll.value=false
    halfchecked.value=false
  }
  else{
    if(list.length==initList.value.length) {
      halfchecked.value=false
      checkedAll.value=true
    }
    else  {
      checkedAll.value=false
      halfchecked.value=true
    }
  }
},{immediate:true})


function removeSortable(){
	sortableInstance && sortableInstance.destroy && sortableInstance.destroy()
	sortableInstance=null
}

function initSortable (){
	const dragArea = listElRef.value.$el
	const ops = {
		animation: 100,
		dataIdAttr: 'itemId',
    handle:'.tcs-draggable',
		onEnd: (_evt: any) => {
			sortKeys.value=sortableInstance.toArray()
			// console.log(sortableInstance.toArray())
		},
	}
	const sortableInstance = sortable.create(dragArea, ops)
}

function handleCheckedChange(e:any){
  //console.log(e)
}

function handleCheckedAllChange(e:any){
  // console.log(e)
  checkedList.value=[]
  halfchecked.value=false
  if(e)
  list.value.forEach(v=>{
    checkedList.value.push(v[idKey])
  })
  else
  list.value.forEach(v=>{
    if(v.fixed) checkedList.value.push(v[idKey])
  })
}

function hasChange(){
	if(sortKeys.value.length){
		const _checkList:string[]=[]
		sortKeys.value.forEach((v:string)=>{
			if(checkedList.value.includes(v)) _checkList.push(v)
		})
		checkedList.value=_checkList
	}
	if (JSON.stringify(preCheckedList.value) == JSON.stringify(checkedList.value)) return false
	return true
}

function handleConfirm() {
	visible.value = false
	if(!hasChange()) {sortKeys.value=[];return}
	//console.log('333333333')
  const listMap: ObjType = {}
  initList.value.forEach((v) => (listMap[v[idKey]] = v))
	const temp_list: ObjType[] = []
	checkedList.value.forEach((id) => {
		const item = listMap[id]
		if (item) temp_list.push(item)
	})
	emits('confirm', temp_list)
	preCheckedList.value = checkedList.value
	sortKeys.value=[]
}

function handleReset() {
	visible.value = false
	checkedList.value=initCheckedList.value
	if(!hasChange()) {sortKeys.value=[];return}
	// console.log('111111111')
	preCheckedList.value=checkedList.value
	sortKeys.value=[]
	emits('confirm',initList.value);
	[...listElRef.value.$el.children].forEach(v=>v.remove())
	list.value=[]
	nextTick(()=>{list.value=deepClone(initList.value,false)})
}

</script>

<template>
  <el-popover
    placement="bottom-start"
    trigger="click"
    v-model:visible="visible"
  >
    <template #reference>
      <el-button >表格列设置</el-button>
    </template>
    
    <div class="content">
      <div class="header" style="display: flex;justify-content: flex-end;">
        <div class="close" @click="visible=false">
          <el-icon :size="20"><Close /></el-icon>
        </div>
			</div>
      <div class="checkedAll">
        <el-checkbox :indeterminate="halfchecked" v-model="checkedAll" @change="handleCheckedAllChange" >
        <span :style="{color:primaryColor_hex}">全选/反选</span>
        </el-checkbox>
      </div>

      <el-scrollbar :max-height="250">
        <div class="checkedList" >
          <el-checkbox-group ref="listElRef"
          v-model="checkedList"
          @change="handleCheckedChange"
          >
        <template v-for="(item,index) in list" >
          <div  :class="{checkedItem:true,'tcs-draggable':!item.fixed}" :itemId="item[idKey]">
            <el-checkbox  :key="index" :label="item[idKey]" :disabled="!!item.fixed">
              {{item.label}}
            </el-checkbox>
          </div>
        </template>
          </el-checkbox-group>
        </div>
     </el-scrollbar>

      <div class="operation">
        <div class="right" style="display: flex;">
          <el-button size="small" @click="handleReset">重置</el-button>
          <el-button type="primary" size="small" @click="handleConfirm">确定</el-button>
        </div>
      </div>
    </div>

  </el-popover>
</template>

<style scoped lang="scss">
.operation{
  display: flex;
  justify-content: right;
  margin-top: 10px;
}
</style>